﻿using System;
using GTA;
using offline2048;
using UnityEngine;
using UnityEngine.UI;
using TMPro;

public class MainPanel : UIBoxBase
{
    public TextMeshProUGUI CoinText;
    public TextMeshProUGUI CurrentScoreText;
    public TextMeshProUGUI BestScoreText;
    public TextMeshProUGUI TargetText;

    public GameObject SoundImage;
    public GameObject MuteImage;
    public GameObject PrizeDialog;
    //public GameObject DoubleButton;
    public AutoCloseTip m_ImgNoStoneTip;
    public TextMeshProUGUI m_GiftBoxShutDownTime;
    private TimeSpan m_OffsetTimeDifference;
    private float m_CurShutDownTimeInterval;
    public CoinAnimation m_IconFly;
    public CoinAnimation m_DollerIconFly;
    public GameObject m_GiftBox;
    private bool m_IsPlayGiftBoxAnime;
    //新功能添加
    public GameObject m_TopStoneIcon;
    public GameObject m_TopDollerIcon;

    public GameObject m_BestScore;
    public Button m_BtnUIShop;
    public Button m_BtnUIShop2;
    public Button m_BtnOrganicShop;

    public GameObject m_RandomOrganic1;
    public GameObject m_RandomOrganic2;

    public GameObject m_RandomNoOrganic;

    public TextMeshProUGUI m_TxtPrizeReceive;
    public TextMeshProUGUI m_TxtTriplePrizeReceive;
    
    private int m_CurPrizeReceive;
    //钻石和doller的Icon
    public GameObject m_StonePic1;
    public GameObject m_DollerPic1;
    public GameObject m_StonePic2;
    public GameObject m_DollerPic2;
    public GameObject m_StonePic3;
    public GameObject m_DollerPic3;

    public Text m_TxtShopTitle;
    public Text m_TxtShopCM;
    private void Start()
    {
        EventManager2.UpdateCoinChange += UpdateCoinChange;
        m_IsPlayGiftBoxAnime = false;
        m_OffsetTimeDifference = GameManager.instance.GetGiftBoxShutdownTime() - GameManager.instance.TimeStampToDateUTC();
        m_GiftBoxShutDownTime.text = $"{(int)m_OffsetTimeDifference.TotalHours:00}:{m_OffsetTimeDifference.Minutes:00}";
        m_CurShutDownTimeInterval = 61;
        m_IconFly.gameObject.SetActive(false);
        m_DollerIconFly.gameObject.SetActive(false);
        LeanTween.delayedCall(0.1f, () =>
        {
            CoinText.text = GameManager.instance.CurrentData.CoinNumber.ToString();
            CurrentScoreText.text = GameManager.instance.CurrentData.CurrentScore.ToString();
            BestScoreText.text = GameManager.instance.CurrentData.BestScore.ToString();
            //GameManager.instance.CurrentData.CoinNumber = 100;
            if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
            {
                BestScoreText.gameObject.SetActive(true);
            }
            else
            {
                BestScoreText.gameObject.SetActive(false);
            }
        });
        m_BtnUIShop.onClick.AddListener(OnClickUIShopBtn);
        m_BtnUIShop2.onClick.AddListener(OnClickUIShopBtn);
        m_BtnOrganicShop.onClick.AddListener(OnClickOrganicShopBtn);
        SetUIActiveByUserLayer();
        SetShopBtnData();
    }

    private void OnClickOrganicShopBtn()
    {
        if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
        {
            MainManager.Instance.ShowOganicShop();
        }
        else
        {
            MainManager.Instance.ShowUIShop();
        }
    }

    private void OnClickUIShopBtn()
    {
        if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
        {
            
        }
        else
        {
            MainManager.Instance.ShowUIShop();
        }
    }
    
    private void SetUIActiveByUserLayer()
    {
        //根据用户分层做显示
        if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
        {
            m_TopStoneIcon.SetActive(true);
            m_TopDollerIcon.SetActive(false);

            m_BestScore.SetActive(true);
            //m_BtnUIShop.gameObject.SetActive(false);
            
            m_RandomOrganic1.SetActive(true);
            m_RandomOrganic2.SetActive(true);

            m_RandomNoOrganic.SetActive(false);
            
            m_StonePic1.SetActive(true);
            m_DollerPic1.SetActive(false);
            
            m_StonePic2.SetActive(true);
            m_DollerPic2.SetActive(false);
            m_StonePic3.SetActive(true);
            m_DollerPic3.SetActive(false);
        }
        else
        {
            m_TopStoneIcon.SetActive(false);
            m_TopDollerIcon.SetActive(true);

            m_BestScore.SetActive(false);
            //m_BtnUIShop.gameObject.SetActive(true);
            
            m_RandomOrganic1.SetActive(false);
            m_RandomOrganic2.SetActive(false);

            m_RandomNoOrganic.SetActive(true);
            
            m_StonePic1.SetActive(false);
            m_DollerPic1.SetActive(true);
            
            m_StonePic2.SetActive(false);
            m_DollerPic2.SetActive(true);
            m_StonePic3.SetActive(false);
            m_DollerPic3.SetActive(true);
        }
    }
    
    private void Update()
    {
        m_CurShutDownTimeInterval += Time.deltaTime;
        if (m_CurShutDownTimeInterval >= 1)
        {
            m_CurShutDownTimeInterval = 0;
            m_OffsetTimeDifference = GameManager.instance.GetGiftBoxShutdownTime() - GameManager.instance.TimeStampToDateUTC();
            int compareResult = GameManager.instance.GetGiftBoxShutdownTime().CompareTo(GameManager.instance.TimeStampToDateUTC()); // 比较您的DateTime数据与当前时间戳
            if (compareResult > 0)
            {
                m_GiftBoxShutDownTime.text = $"{(int)m_OffsetTimeDifference.TotalHours:00}:{m_OffsetTimeDifference.Minutes:00}";
            }
            else
            {
                m_GiftBoxShutDownTime.text = "free";
            }
        }
        
    }

    private void OnEnable()
    {
        EventManager2.OnScoreChange += OnCurrentScoreChange;
        EventManager2.OnBestScoreChange += OnBestScoreChange;
        EventManager2.OnCoinChange += OnCoinChange;
        
        EventManager2.OnTargetChange += OnTargetChange;

        EventManager2.SetShopBtnData += SetShopBtnData;
        
        //EventManager2.RewardAdsPlaySuccess += OnRewardAdsPlaySuccess;

        EventManager2.SetUIActiveByUserLayer += SetUIActiveByUserLayer;
    }

    private void OnDisable()
    {
        EventManager2.OnScoreChange -= OnCurrentScoreChange;
        EventManager2.OnBestScoreChange -= OnBestScoreChange;
        EventManager2.OnCoinChange -= OnCoinChange;
        
        EventManager2.SetShopBtnData -= SetShopBtnData;
        
        //EventManager2.RewardAdsPlaySuccess -= OnRewardAdsPlaySuccess;
        EventManager2.OnTargetChange -= OnTargetChange;
        
        EventManager2.SetUIActiveByUserLayer -= SetUIActiveByUserLayer;
    }

    private void SetShopBtnData()
    {
        ShopListItemData _data = UIShopManager.Instance.GetShowItemData();
        if (_data != null)
        {
            if (_data.m_ItemState == (int)UIShopManager.PaypalAndCashingItemType.phase_1)
            {
                m_BtnUIShop.gameObject.SetActive(true);
                m_TxtShopTitle.text = $"${_data.m_Index * 1000}";
                m_TxtShopCM.text = $"{_data.m_CMCountProgress}/50";
            }
            else if (_data.m_ItemState == (int)UIShopManager.PaypalAndCashingItemType.phase_5)
            {
                m_BtnUIShop.gameObject.SetActive(true);
                m_TxtShopTitle.text = $"${_data.m_Index * 1000}";
                m_TxtShopCM.text = $"{_data.m_Phase5CMCount}/50";
            }
        }
        else
        {
            m_BtnUIShop.gameObject.SetActive(false);
        }
    }
    
    public void OnColumnButtonClick(int index)
    {
        GameManager.instance.OnColumnClick(index);
    }

    public void OnAudioButtonClick()
    {
        MainManager.Instance.AddTestTouch();
        //AdWrapper.Instance.Init();
        if(AudioController.IsSoundMuted())
        {
            AudioController.Play("PanelOpen");
            AudioController.MuteSound(false);
            MuteImage.SetActive(false);
            SoundImage.SetActive(true);
        }
        else
        {
            AudioController.MuteSound(true);
            SoundImage.SetActive(false);
            MuteImage.SetActive(true);
        }
    }

    public void OnRetryButtonClick()
    {
        AudioController.Play("PanelOpen");
        GameManager.instance.RestartGame();

        //AdsManager.instance.PlayInterstitialAds();
    }

    public void OnRankButtonClick()
    {
        AudioController.Play("PanelOpen");
    }

    public void OnShopButtonClick()
    {
        AudioController.Play("PanelOpen");
        //UIManager.instance.ShowBox(UIBoxType.ShopPanel);
    }
    
    
    private void OnCurrentScoreChange(int score)
    {
        CurrentScoreText.text = score.ToString();
    }

    private void OnBestScoreChange(int score)
    {
        if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
        {
            BestScoreText.text = score.ToString();
        }
        else
        {
            BestScoreText.gameObject.SetActive(false);
        }
    }

    private void OnCoinChange(int coinNumber)
    {
        CoinText.text = coinNumber.ToString();
    }

    private void UpdateCoinChange()
    {
        CoinText.text = GameManager.instance.CurrentData.CoinNumber.ToString();
    }
    
    private void OnTargetChange(int target)
    {
        PrizeDialog.SetActive(true);
        TargetText.text = Utility.CellNumber(target);
        int _target = Utility.CellNumberByInt(target);

        if (!UserLayerManager.Instance.IsOrganic() && UserLayerManager.Instance.GetCurrentUserLayer() != UserLayerManager.UserLayerType.None)
        {
            if (_target == 256)
            {
                m_CurPrizeReceive = 5;
                m_TxtPrizeReceive.text = $"+{m_CurPrizeReceive}";
                m_TxtTriplePrizeReceive.text = $"+{m_CurPrizeReceive * 3}";
            }
            else if (_target == 512)
            {
                m_CurPrizeReceive = 10;
                m_TxtPrizeReceive.text = $"+{m_CurPrizeReceive}";
                m_TxtTriplePrizeReceive.text = $"+{m_CurPrizeReceive * 3}";
            }
            else if (_target == 1024)
            {
                m_CurPrizeReceive = 15;
                m_TxtPrizeReceive.text = $"+{m_CurPrizeReceive}";
                m_TxtTriplePrizeReceive.text = $"+{m_CurPrizeReceive * 3}";
            }
            else if (_target == 2048)
            {
                m_CurPrizeReceive = 20;
                m_TxtPrizeReceive.text = $"+{m_CurPrizeReceive}";
                m_TxtTriplePrizeReceive.text = $"+{m_CurPrizeReceive * 3}";
            }
        }
        
        //if (AdsManager.instance.CanPlayRewardAds())
        //{
        //    DoubleButton.SetActive(true);
        //}
        //else
        //{
        //    DoubleButton.SetActive(false);
        //}

    }

    void OnDestroy()
    {
        EventManager2.UpdateCoinChange -= UpdateCoinChange;
    }

    public void OnDoubleButtonClick()
    {
        ADSHelper.ShowRewardedVideoAd((status) =>
        {
            if (status == true)
            {
                if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
                {
                    m_CurPrizeReceive = 30;
                }
                PrizeDialog.SetActive(false);
                GameManager.instance.CurrentData.CoinNumber += m_CurPrizeReceive * 3;
                ParticleManager.instance.PlayPrizeAanimation();
                UpdateCoinChange();
                SetShopBtnData();
            }
        }, ERVType.OFFLINE2048.ToString());
        //AdsManager.instance.PlayRewardAds(AdsType.DoubleGift);
    }

    public void OnReceiveButtonClick()
    {
        PrizeDialog.SetActive(false);

        if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
        {
            m_CurPrizeReceive = 20;
        }
        
        int _noAdTenTimes = PlayerPrefsManager.GetInt(PlayerPrefsManager.USER_NO_AD_TEN_TIMES);
        _noAdTenTimes++;
        if (_noAdTenTimes >= 5)
        {
            UserLayerManager.Instance.ChangeUserLayer(UserLayerManager.UserLayerType.LowUser);
        }
        PlayerPrefsManager.SetInt(PlayerPrefsManager.USER_NO_AD_TEN_TIMES, _noAdTenTimes);
        
        GameManager.instance.CurrentData.CoinNumber += m_CurPrizeReceive;
        if (MainManager.Instance.m_OpenInterCMTime >= 120)
        { 
            MainManager.Instance.m_OpenInterCMTime = 0;
            ADSHelper.ShowInterstitialAd("", AdsDataMgr.EInterstitiaFireScene.offline2048);
        }
        UpdateCoinChange();
        //AdsManager.instance.PlayInterstitialAds();
        ParticleManager.instance.PlayPrizeAanimation();

    }

    /*private void OnRewardAdsPlaySuccess(AdsType adsType)
    {
        if (adsType != AdsType.DoubleGift) return;

        GameManager.instance.CurrentData.CoinNumber += 50;
        ParticleManager.instance.PlayPrizeAanimation();
    }*/

    public void OnHammerButtonClick()
    {
        if(GameManager.instance.CurrentData.CoinNumber >= 100)
        {
            HideBox();
            AudioController.Play("Hammer");
            UIManager.instance.ShowBox(UIBoxType.HammerPanel);
        }
        else
        {
            m_ImgNoStoneTip.gameObject.SetActive(true);
            m_ImgNoStoneTip.m_ShutDownTime = 1f;
            //UIManager.instance.ShowBox(UIBoxType.ShopPanel);
        }
    }

    public void OnRandomButtonClick()
    {
        if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
        {
            if (GameManager.instance.CurrentData.CoinNumber >= 50)
            {
                GameManager.instance.CreateCurrentCell();
                GameManager.instance.CurrentData.CoinNumber -= 50;
                UpdateCoinChange();
            }
        }
        else
        {
            ADSHelper.ShowRewardedVideoAd((status) =>
            {
                if (true)
                {
                    GameManager.instance.CreateCurrentCell();
                    SetShopBtnData();
                    UpdateCoinChange();
                }
            }, ERVType.OFFLINE2048.ToString());
        }
    }

    public void OnClickGiftBoxBtn()
    {
        if (!m_IsPlayGiftBoxAnime)
        {
            m_IsPlayGiftBoxAnime = true;
            LeanTween.scale(m_GiftBox, Vector3.one * 1.2f, 0.15f).setEase(LeanTweenType.easeOutCubic).setOnComplete(() =>
            {
                LeanTween.scale(m_GiftBox, Vector3.one, 0.15f).setEase(LeanTweenType.easeOutCubic).setOnComplete(() =>
                {
                    m_IsPlayGiftBoxAnime = false;
                });
            });

            DateTimeOffset givenTimestamp = GameManager.instance.GetGiftBoxShutdownTime();// 假设这是你的给定时间戳
            // 获取当前时间戳
            DateTimeOffset currentTimestamp = DateTimeOffset.Now;
            if (givenTimestamp < currentTimestamp)
            {
                //给定时间戳比当前时间戳早 可以领奖
                GameManager.instance.CurrentData.CoinNumber += 100;
                //飞行特效
                if (UserLayerManager.Instance.IsOrganic() || UserLayerManager.Instance.GetCurrentUserLayer() == UserLayerManager.UserLayerType.None)
                {
                    m_IconFly.gameObject.SetActive(true);
                    m_IconFly.InitAnimation2(new Vector3(50,-1800));
                }
                else
                {
                    m_DollerIconFly.gameObject.SetActive(true);
                    m_DollerIconFly.InitAnimation2(new Vector3(50,-1800));
                }
                //保存当前时间戳
                GameManager.instance.SaveGiftBoxShutdownTime();
            }
            else
            {
                //nothing
            }   
        }
    }
}
